package com.joeljhou.project.core.data;

import com.joeljhou.project.core.SerialPortManager;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Observable;
import java.util.Random;

public class DataReceiver extends Observable {

    private String[] dataArray = new String[]{"01 03 0B 00", "01 03 7A 00", "01 03 2C 27", "01 03 0B 04", "01 03 C2 0D"};

    public void receiveData() {
        //模拟
        if (SerialPortManager.getFlag()) {
            Thread thread2 = new Thread(() -> {
                // 获取一个输入流，从串口读取数据
                InputStream in = SerialPortManager.getConnectionPort().getInputStream();

                while (true) {
                    //休眠1000ms
                    try {
                        Thread.sleep(1000);
                        setChanged();
                        notifyObservers(dataArray[new Random().nextInt(5)]);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread2.start();
            return;
        }

        Thread thread = new Thread(() -> {
            // 获取一个输入流，从串口读取数据
            InputStream in = SerialPortManager.getConnectionPort().getInputStream();

            while (true) {
                try {
                    //休眠100ms
                    Thread.sleep(100);
                    int available = in.available();
                    if (available == 0) {
                        continue;
                    }

                    // 从串口读取数据
                    byte[] buffer = new byte[in.available()];
                    in.read(buffer);
                    // 处理数据
                    String receivedData = String.format("%02x", buffer[0]).toUpperCase(Locale.ROOT)
                            + " "
                            + String.format("%02x", buffer[1]).toUpperCase(Locale.ROOT)
                            + " "
                            + String.format("%02x", buffer[2]).toUpperCase(Locale.ROOT)
                            + " "
                            + String.format("%02x", buffer[3]).toUpperCase(Locale.ROOT);
                    setChanged();
                    notifyObservers(receivedData);
                } catch (InterruptedException e) {
                    //此处处理异常
                    e.printStackTrace();
                    break;
                } catch (IOException e) {
                    //此处处理异常
                    e.printStackTrace();
                    break;
                }
            }
        });

        thread.start();
    }
}
